<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <!--  工资查询 -->
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入 Element UI 样式文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.6/lib/theme-chalk/index.css">
    <!-- 引入 Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入 Element UI 脚本文件 -->
    <script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.6/lib/index.js"></script>
    <!-- 引入 axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- 引入 导航栏css 需要通过服务器请求-->
    <link rel="stylesheet" href="/css/nav.css" />
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .sea {
            margin: 20px 25px 0px 22px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        body::-webkit-scrollbar {
            /* 隐藏滚动条 */
            display: none;
            /* Chrome, Safari, and Opera */
        }

        /*分页*/
        .block {
            padding: 10px;
            background: #fff;
            border: none;
            text-align: right;
            width: 100%;
            height: 30px;
            z-index: 2;
            position: fixed;
            bottom: 0;
            right: 0;
            box-shadow: 0px 0px 10px 1px #a0a0a0;
        }

        /* 表格数据列 */
        .ellipsis-text {
            white-space: nowrap;
            /* 不换行 */
            overflow: hidden;
            text-overflow: ellipsis;
            /* 显示省略号 */
        }
        .el-dialog__header{ /* 弹窗头部 */
            padding: 20px 20px 0;
        }
        .el-dialog--center .el-dialog__body{
            padding: 0px 25px 30px;
        }
        .el-divider--horizontal{ /* 水平分割线 */
            margin: 12px 0  ;
        }
        .el-divider{
            background-color: #ea8682;
        }
    </style>
</head>

<body>
<div id="app">
    <div th:replace="nav :: nav"></div>
    <!-- 水印层 -->
    <div class="watermark">{{userNowName}} {{user}}</div>
    <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
        <div style="margin-top: 70px;"></div>
        <div class="sea">
            <!--     面包屑导航 -->
            <div>
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item><a th:href="@{/}">首页</a></el-breadcrumb-item>
                    <el-breadcrumb-item>工资管理</el-breadcrumb-item>
                    <el-breadcrumb-item>工资查询</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <!-- 搜索-->
            <div class="select" style="display: flex;">
                <div >
                    <el-input v-if="!userRole2" placeholder="请输入员工姓名" v-model="selectName" class="input-with-select" size="mini" clearable></el-input>
                </div>
                <div style=" margin: 0 20px">
                    <el-select v-model="selectMonth" placeholder="请选择工资月份" size="mini" clearable >
                        <el-option  v-for="item in options"  :key="item.value"  :label="item.label" :value="item.value"> </el-option>
                    </el-select>
                </div>
                <el-button slot="append" size="mini" icon="el-icon-search" @click="searchList()">查询</el-button>
            </div>
            <!-- 批量导出 重置 -->
            <div>
                <el-row>
                    <el-button size="small" type="primary" icon="el-icon-circle-check" @click="ALLDetail()">批量导出</el-button>
                    <el-button size="small" type="warning" icon="el-icon-refresh" @click="reload()">重置</el-button>
                </el-row>
            </div>
        </div>
        <!-- stripe属性可以创建带斑马纹的表格； border表格边框 -->
        <el-table size="mini" :data="originalData" stripe style="width: 100%;  margin: 0 0 50px;" @selection-change="handleSelectionChange">
            <!-- #选中 -->
            <el-table-column type="selection" width="45" align="center"></el-table-column>
            <!-- 员工编号 -->
            <el-table-column prop="user_id" label="员工编号" align="center" width="80"></el-table-column>
            <!-- 员工姓名 -->
            <el-table-column  prop="z_name" label="员工姓名" align="center" width="90"></el-table-column>
            <!-- 所属部门 --> 
            <el-table-column label="所属部门" width="150" align="center"
                :filters="[{ text: '总裁办', value: '总裁办' }, { text: '战略规划部', value: '战略规划部' }, { text: '人力资源中心', value: '人力资源中心' }, { text: '法务部', value: '法务部' },{ text: 'IT部', value: 'IT部' }, { text: '集团供应链', value: '集团供应链' },  { text: '国际营销系统', value: '国际营销系统' }, { text: '国内营销系统', value: '国内营销系统' },{ text: 'POCT系统', value: 'POCT系统' }]"
                :filter-method="filterDepartment" filter-placement="bottom-end">
                <template slot-scope="scope">
                    <span v-if="scope.row.department">{{ scope.row.department }}</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <!-- 工资月份 -->
            <el-table-column prop="month" label="工资月份" align="center" width="100"></el-table-column>
            <!-- 基本工资 -->
            <el-table-column prop="basicSalary" label="基本工资" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.basicSalary !== '0' ? '#008500' : 'inherit' }">{{ scope.row.basicSalary }}</span>
                </template>
            </el-table-column>
            <!-- 全勤工资 -->
            <el-table-column prop="fullSalary" label="全勤工资" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.fullSalary !== '0' ? '#008500' : 'inherit' }">{{ scope.row.fullSalary }}</span>
                </template>
            </el-table-column>
            <!-- 迟到扣款 -->
            <el-table-column prop="lateDeduction" label="迟到扣款" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.lateDeduction !== '0' ? 'red' : 'inherit' }">{{ scope.row.lateDeduction }}</span>
                </template>
            </el-table-column>
            <!-- 请假扣款 -->
            <el-table-column prop="leaveDeduction" label="请假扣款" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.leaveDeduction !== '0' ? 'red' : 'inherit' }">{{ scope.row.leaveDeduction }}</span>
                </template>
            </el-table-column>
            <!-- 出差补贴 -->
            <el-table-column prop="travelAllowance" label="出差补贴" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.travelAllowance !== '0' ? '#008500' : 'inherit' }">{{ scope.row.travelAllowance }}</span>
                </template>
            </el-table-column>
            <!-- 个税扣款 -->
            <el-table-column prop="taxDeduction" label="个税扣款" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.taxDeduction !== '0' ? 'red' : 'inherit' }">{{ scope.row.taxDeduction }}</span>
                </template>
            </el-table-column>
             <!-- 五险一金 -->
             <el-table-column prop="five_one" label="五险一金" align="center" width="95">
                <template slot-scope="scope">
                    <span :style="{ color: scope.row.five_one !== '0' ? 'red' : 'inherit' }">{{ scope.row.five_one }}</span>
                </template>
             </el-table-column>
             <!-- 实发合计 -->
             <el-table-column prop="sumSalary" label="实发合计" align="center" width="95">
                <template slot-scope="scope">
                    <span style="color: rgb(0, 13, 255);font-weight: bold;">{{ scope.row.sumSalary }}</span>
                </template>
             </el-table-column>
            <!-- 创建时间 -->
            <el-table-column prop="time" label="创建时间"  width="200" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time"></i><span style="margin-left: 5px">{{ scope.row.time }}</span>
                </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-link type="danger" style="font-size: 10px;" @click="Detail(scope.$index, scope.row);">导出</el-link>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="block">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="pageNum" :page-sizes="[15,30,50,100,200]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>


    </div>
</div>
</body>
<script>
    new Vue({
        el: '#app',
        data: {
            user: JSON.parse(localStorage.getItem("user")),
            userRole1: '',//	administrator的权限,boolen
            userRole2: '',//  user的   boolen
            userNowdata: '', // 当前用户的所有数据
            activeIndex: '3-1',
            userNowName: '',//当前用户姓名

            loading: true, //加载动画
            originalData: [], // 当前页面数据
            total: 0, //总条数
            pageNum: 1, //第几页
            pageSize: 15, //每页几条数据

            options: [{ // 日志类型
                value: '2023-11',
                label: '2023-11'
            }, {
                value: '2023-10',
                label: '2023-10'
            }],
            month:'',
            z_name:'',
            selectName:'',//查询姓名
            selectMonth:'',//查询月份
            multipleSelection: [],//表格选择项的数组

            logData: {// 日志信息 (公用)
                operator: '',
                logType: '',
                recordTime: '',
                operatorIP: "192.168.2.21",
                requestType: '',
                requestInterface: '',
                requestParameters: '',
                responseType: '',
                resdata:'',
                error:''
            },

        },
        created() {
            this.getUserRole(); // 加载用户权限
            // 模拟加载动画
            setTimeout(() => {
                this.loading = false;
            }, 500); // 1秒后执行
        },
        methods: {
            // 账号退出(通用）
            logoutButton() {
                axios.get("/user/logout")
            },
            // 用户权限（通用）
            getUserRole() {
                axios.get("/user/now?username=" + this.user)
                    .then(res => {
                        this.userRole1 = (res.data.UserNowdata[0].role === 'administrator')
                        this.userRole2 = (res.data.UserNowdata[0].role === 'user')
                        this.userNowdata = res.data.UserNowdata
                        this.userNowName = this.userNowdata[0].z_name;
                        this.getSalaryList();
                        // 访问请求的相关信息,写进日志
                        this.getLog(res);
                        axios.post('/log', {  ...this.logData, logType: '操作日志'} )
                    });
            },
            // 重置页面
            reload() {
                window.location.reload()
            },
            // 分页
            handleSizeChange(val) {
                this.pageSize = val;
                console.log(`每页 ${this.pageSize} 条`);
                this.getSalaryList();
            },
            handleCurrentChange(val) {
                this.pageNum = val;
                console.log(`当前页: ${val}`);
                this.getSalaryList();
            },
            // 筛选
            filterDepartment(value,row){
                return row.department === value;
            },
            // 请求 工资 分页数据
            getSalaryList() {
                if (this.userRole2) { // 因为User权限没有查询姓名功能，所有将 this.z_name 赋值为当前用户 ，实现只加载当前用户数据功能
                    this.z_name = this.userNowName
                }
                axios.get("/salary/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&z_name=" + this.z_name + "&month=" + this.month)
                    .then(res => {
                        this.originalData = res.data.salaryData;
                        this.total = res.data.total;
                        // 访问请求的相关信息,写进日志
                        this.getLog(res);
                        axios.post('/log', { ...this.logData, logType: '操作日志' })
                    });
            },
            // 单个/组合搜索
            searchList() {
                this.pageNum = 1; //不先把页面等于1的话，有些会搜索不到
                this.z_name = this.selectName
                this.month = this.selectMonth
                this.getSalaryList();
            },
            // 单个导出为Excel
            Detail(index, row) {       
                // 定义 headerMap 和 rows
                const headerMap = {
                    field1: '员工编号', field2: '员工姓名', field3: '所属部门', field4: '工资月份', field5: '基本工资', field6: '全勤工资',
                    field7: '迟到扣款', field8: '请假扣款', field9: '出差补贴', field10: '个税扣款', field11: '五险一金', field12: '实发合计', field13: '创建时间',};
                const rows = [{
                    field1: row.user_id, field2: row.z_name, field3: row.department, field4: row.month, field5: row.basicSalary, field6: row.fullSalary,
                    field7: row.lateDeduction, field8: row.leaveDeduction, field9: row.travelAllowance, field10: row.taxDeduction, field11: row.five_one, field12: row.sumSalary, field13: row.time,}];
                // 将 headerMap 和 rows 放在同一个对象中
                const requestBody = { headerMap: headerMap, rows: rows };
                // 设置文件名字
                const fileName = row.z_name + row.month + '工资明细.xlsx';
                // 调用 postExcel 
                this.postExcel(requestBody, rows, fileName);            
            },
            // 导出函数 (通用)
            postExcel(requestBody, row,fileName) {               
                axios.post('/salary/export', requestBody, { responseType: 'arraybuffer' })
                    .then(response => {
                        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                        const link = document.createElement('a');//获取文件 blob 的 URL
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName; // 文件名字
                        document.body.appendChild(link);
                        link.click();  // 触发下载按钮
                        document.body.removeChild(link);
                        this.$message({ message: '导出成功！', type: 'success' });
                        // 访问请求的相关信息,写进日志
                        this.getLog(response);
                        axios.post('/log', { ...this.logData, logType: '操作日志' })
                    })
                    .catch(error => {
                        console.error(error);
                        // 访问请求的相关信息,写进日志
                        this.getLog(error);
                        axios.post('/log', { ...this.logData, logType: '错误日志' })
                    });
            },
            // 当表格选择项发生变化时会触发该事件
            handleSelectionChange(val) {
                this.multipleSelection =val
                console.log(this.multipleSelection)                 
            },
            //批量导出
            ALLDetail(){
                const headerMap = {
                    field1: '员工编号', field2: '员工姓名', field3: '所属部门', field4: '工资月份', field5: '基本工资', field6: '全勤工资',
                    field7: '迟到扣款', field8: '请假扣款', field9: '出差补贴', field10: '个税扣款', field11: '五险一金', field12: '实发合计', field13: '创建时间',};
               // 使用 map 函数将 multipleSelection 数组中的每个元素映射为一个对象，对象包含所需的字段。
                const rows = this.multipleSelection.map(row => ({ 
                    field1: row.user_id, field2: row.z_name, field3: row.department, field4: row.month, field5: row.basicSalary, field6: row.fullSalary,
                    field7: row.lateDeduction, field8: row.leaveDeduction, field9: row.travelAllowance, field10: row.taxDeduction, field11: row.five_one, field12: row.sumSalary, field13: row.time, }));
                const requestBody = { headerMap: headerMap, rows: rows };
                const fileName ='批量工资明细.xlsx';
                // 调用 postExcel 
                let row = {};  // 为了可以调用postExcel方法
                this.postExcel(requestBody, row, fileName);         
            },
            // 从接口的res 获取日志 (公用）
            getLog(res) {
                this.logData.operator = this.user, // 操作者
                this.logData.recordTime = new Date().toLocaleString(), // 记录时间
                // this.logData.operatorIP = 操作者ip
                this.logData.requestType = res.config.method; // 请求类型
                this.logData.requestInterface = '/api' + res.config.url;// 请求URL
                this.logData.requestParameters = res.config.data; // 请求参数
                this.logData.responseType = res.headers['content-type'];// 实体主体的媒体类型
                if(res.data){ // 响应参数
                    this.logData.resdata = JSON.stringify(res.data).substring(0, 5000);// 数组转成字符串，最大写入量5000
                    this.logData.error=''
                }else{ // 错误信息
                    this.logData.resdata =''
                    this.logData.error =  JSON.stringify(res).substring(0, 5000)
                }
            },
        },
    });
</script>